import React, { Component } from 'react';
import exceed from 'utils/apimap';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Tab, Balloon } from '@teamix/ui';
import { Header, Body, BodyContent, OperationBar, Content, ButtonIcon } from '@alife/devops-ui';
import ListEmpty from 'atComponents/ListEmpty';
import ListLoading from 'atComponents/ListLoading';
import * as actions from '../actions/index';
import * as rootActions from 'pages/index/actions';
import MrInfo from './mrInfo';
import CommitInfo from './commitInfo';
import { getProjectServices } from 'api';
import { ENUM, ORGANIZATION_ADMIN_ROLES, PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import { navigate } from 'utils/router';
import Help from './help';
import docs from 'utils/docs';
import track, { enterPage, Perf } from 'utils/track';
import Waiting from './waiting';
import dayjs from 'dayjs';
import utils from 'utils';
import intl from '../../../../../../../locale';

const tabItems = [
  {
    value: 'commits',
    label: intl.get({
      id: 'code-assets.projectInsight.containers.root.CodeSubmission',
      defaultMessage: '代码提交',
    }),
  },

  {
    value: 'codereview',
    label: intl.get({
      id: 'code-assets.projectInsight.containers.root.CodeReview',
      defaultMessage: '代码评审',
    }),
  },
];

const prefix = 'project-statistics';
class Root extends Component {
  state = {
    project_report_enable: false,
    isMock: null,
  };

  componentDidMount() {
    this.setState({
      isLoadingService: true,
    });

    this.getServiceInfo();
    const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
    if (isTooLarge && document.getElementById('container')) {
      document.getElementById('container').classList.add('has-too-large-tip');
    }

    enterPage('Repo-Insight', {
      sendPerf: false,
    });
  }

  componentDidUpdate(prevProps) {
    if (prevProps.repoSize !== this.props.repoSize) {
      const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
      if (isTooLarge && document.getElementById('container')) {
        document.getElementById('container').classList.add('has-too-large-tip');
      }
    }
  }

  componentWillUnmount() {
    if (document.getElementById('container')) {
      document.getElementById('container').classList.remove('has-too-large-tip');
    }
  }

  isAdmin = () => {
    const { projectInfo: project } = this.props;
    const { user_role } = window.FORCE.organization;
    return (
      access(ORGANIZATION_ADMIN_ROLES, user_role) ||
      access(PROJECT_ADMIN_ROLES, ENUM.access_level[project.access_level])
    );
  };

  getServiceInfo = () => {
    const { projectInfo = {} } = this.props;
    if (JSON.stringify(projectInfo) === '{}') {
      const { pathResource } = window.FORCE;
      exceed
        .fetch({
          api: 'projects.single.get',
          params: {
            id: pathResource.id,
          },
        })
        .then((res) => {
          this.getServiceInfo2(res);
        })
        .fail((err) => {
          console.error(err);
          this.getServiceInfo2(projectInfo);
        });
    } else {
      this.getServiceInfo2(projectInfo);
    }
  };

  getServiceInfo2 = (exceedProjectInfo) => {
    getProjectServices()
      .then((result) => {
        const serviceData = result.integration_service_setting || {};
        const { project_report } = serviceData;

        this.setState({
          project_report_enable: project_report ? project_report.enabled : false,
          isLoadingService: false,
          change_date: project_report ? project_report.change_date : '',
        });

        const projectInfo = exceedProjectInfo;
        const { demo_project = false } = projectInfo;

        const isWaiting =
          project_report.change_date &&
          dayjs(project_report.change_date).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD');
        if (!isWaiting && project_report && project_report.enabled) {
          this.setState({
            isMock: false,
          });

          this.props.getTotalCommitData();
          this.props.getDetailCommitData();
          this.props.getTotalMrData();
          this.props.getDetailMrData();
          this.props.getCommentSummaryData();
        } else if (isWaiting && project_report && project_report.enabled && demo_project) {
          this.setState({
            isMock: true,
          });

          // demo库开启报表，并且还在waiting状态，返回mock数据
          this.props.updateStatisticsData({
            detail_mr: [
              {
                participate_review_count: 1,
                review_commits_count: 0,
                review_latency: 0,
                review_lines_count: 0,
                submit_review_count: 3,
                total_commits_count: 0,
                total_lines_count: 0,
                user_info: {
                  avatar_url:
                    'https://tcs-devops.aliyun.com/thumbnail/111r750d14052724f8e48996c9522f78ce61/w/200/h/200',
                  email: 'accounts_5e7db731d9fb2c003716b5c5@mail.teambition.com',
                  extern_uid: '5e7db73103283833285d495c',
                  id: 15484,
                  name: 'Codeup',
                  state: 'active',
                  username: 'accounts_5e7db731d9fb2c003716b5c5@mail.teambition.com',
                },
              },
            ],

            total_commit: {
              add_line_count_total: 0,
              commits_count_total: 0,
              daily_detail: [],
              del_line_count_total: 0,
            },

            detail_commit: [],
            total_mr: {
              commits_count: 0,
              daily_detail: [],
              review_commits_count: 0,
            },

            comment_summary: {
              comment_count: 0,
              daily_detail: [],
              line_count: 0,
            },

            isLoadingCommit: false,
            isLoadingDetailMr: false,
            isLoadingTotalMr: false,
            isLoadingComment: false,
          });
        }
      })
      .catch((err) => {
        console.error(err);
        this.setState({
          isLoadingService: false,
        });
      });
  };

  toggleTab = (value) => {
    window.location.hash = value;
    track({
      action: value === 'commits' ? 'switch_to_commits_chart' : 'switch_to_review_chart',
      page: 'Charts Page',
      type: '',
      control: '',
    });

    this.props.updateStatisticsData({
      curTab: value,
    });
  };

  renderTagsHeader = () => {
    const { curTab } = this.props;
    return (
      <Tab
        className={`${prefix}-tabs`}
        activeKey={curTab}
        onChange={this.toggleTab}
        animation={false}
      >
        {tabItems.map((item) => {
          return <Tab.Item title={item.label} key={item.value} />;
        })}
      </Tab>
    );
  };

  getMediaListJsx() {
    const { isLoading, curTab, projectInfo = {} } = this.props;
    const { change_date } = this.state;
    const { demo_project } = projectInfo;

    if (isLoading) {
      return <ListLoading className="project-content-loading" />;
    }

    if (
      change_date &&
      dayjs(change_date).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD') &&
      !demo_project
    ) {
      return <Waiting />;
    }
    if (curTab === 'commits') {
      const { isMock } = this.state;
      return isMock !== null ? <CommitInfo {...this.props} isMock={isMock} /> : null;
    } else {
      return <MrInfo {...this.props} />;
    }
  }

  goSetting = () => {
    const { pathResource } = window.FORCE;
    navigate(`/${pathResource.fullPath}/settings/services`, { state: { forceUpdate: true } });
    track({
      action: 'to_turn_on_chart',
      page: 'Charts Page',
      type: '',
      control: '',
    });
  };

  // 跳到源文件
  goProjectFile = () => {
    const { pathResource } = window.FORCE;
    navigate(`/${pathResource.fullPath}`);
  };

  renderEntry = () => {
    const isAdmin = this.isAdmin();
    const isRepoEmpty = window.FORCE.pathResource.isEmpty === 'true';
    return (
      <div className="project-insight-entry">
        <Perf page="Repo-Insight" />
        <div className="bg-img">
          <img src="https://img.alicdn.com/tfs/TB1P1JM1UH1gK0jSZSyXXXtlpXa-798-489.png" alt="" />
        </div>
        <ListEmpty
          type="project"
          content={
            <div className="project-insight-entry-title">
              {intl.get({
                id: 'code-assets.projectInsight.containers.root.InsightIntoRDData',
                defaultMessage: '洞察研发数据，提升企业效能',
              })}
            </div>
          }
          description={
            <div>
              {intl.get({
                id: 'code-assets.projectInsight.containers.root.ProvidesDataTrendsAndReport',
                defaultMessage:
                  '提供数据趋势和报表分析，获取代码库研发活跃度、开发者代码贡献量、代码评审覆盖率等关键指标，助力提升研发效率。',
              })}

              <a
                href={docs('insight')}
                target="_blank"
                onClick={() => {
                  track({
                    action: 'know_more_chart',
                    page: 'Charts Page',
                    type: '',
                    control: '',
                  });
                }}
                rel="noreferrer"
              >
                {intl.get({
                  id: 'code-assets.projectInsight.containers.root.LearnMore',
                  defaultMessage: '了解更多',
                })}
              </a>
            </div>
          }
          btns={
            isAdmin
              ? [
                <Button
                  type="primary"
                  onClick={isRepoEmpty ? this.goProjectFile : this.goSetting}
                  style={{ minWidth: 100 }}
                >
                  {isRepoEmpty
                      ? intl.get({
                          id: 'code-assets.projectInsight.containers.root.InitializeARepository',
                          defaultMessage: '初始化仓库',
                        })
                      : intl.get({
                          id: 'code-assets.projectInsight.containers.root.Enable',
                          defaultMessage: '前往开启',
                        })}
                </Button>,
                ]
              : [
                <Button type="normal" disabled>
                  {intl.get({
                      id: 'code-assets.projectInsight.containers.root.ContactTheAdministratorToEnable',
                      defaultMessage: '联系管理员开启',
                    })}
                </Button>,
                ]
          }
        />
      </div>
    );
  };

  render() {
    const { project_report_enable, isLoadingService } = this.state;
    if (isLoadingService) {
      return null;
    }
    if (!project_report_enable) {
      return this.renderEntry();
    }
    return (
      <>
        <Header
          title={
            <span style={{ display: 'flex', alignItems: 'center' }}>
              {intl.get({
                id: 'code-assets.projectInsight.containers.root.Report',
                defaultMessage: '报表',
              })}
              <Balloon
                align="r"
                trigger={<ButtonIcon name="question-line" text style={{ marginLeft: 8 }} />}
                popupStyle={{
                  maxWidth: 'unset',
                  width: '500px',
                  padding: 20,
                }}
                closable={false}
              >
                <div>
                  {intl.get({
                    id: 'code-assets.projectInsight.containers.help.ToEnsureTheAccuracyOf',
                    defaultMessage: '为了保证报表数据的准确性，请确认以下几点：',
                  })}
                </div>
                <div style={{ marginTop: 4 }}>
                  {intl.get({
                    id: 'code-assets.projectInsight.containers.help.TheEmailConfiguredInThe',
                    defaultMessage: '1. 本地 git config 中配置的 email 和平台已绑定的主邮箱一致；',
                  })}
                </div>
                <div>
                  {intl.get({
                    id: 'code-assets.projectInsight.containers.help.TheSubmissionTimeStatisticsAre',
                    defaultMessage:
                      '2. 提交时间相关统计以本地系统时间为准，请确认本地时间设置正常；',
                  })}
                </div>
                <div className="insight-help-footer">
                  <Button
                    size="small"
                    type="primary"
                    component="a"
                    href={docs('insight')}
                    target="_blank"
                    onClick={this.onCancel}
                  >
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.help.MoreDescription',
                      defaultMessage: '更多说明',
                    })}
                  </Button>
                </div>
              </Balloon>
            </span>
          }
          operation={<Help />}
        />

        <Body>
          <BodyContent>
            <OperationBar>{this.renderTagsHeader()}</OperationBar>
            <Content>
              <div>{this.getMediaListJsx()}</div>
            </Content>
          </BodyContent>
        </Body>
        <Perf page="Repo-Insight" />
      </>
    );
  }
}

export default connect(
  (state) => ({
    ...state.project.projectInsight,
    projectInfo: state.project.root.projectInfo,
    pageInfo: state.root.pageInfo,
  }),

  (dispatch) => bindActionCreators({ ...actions, ...rootActions }, dispatch),
)(Root);
